package com.link.base.base.appduty.service;


import com.link.base.base.appduty.dao.mybatis.mapper.AppDutyMapper;
import com.link.base.base.appduty.model.AppDuty;
import com.link.base.base.appmenuurls.model.AppMenuUrls;
import com.link.base.base.appmenuurls.service.AppMenuUrlsService;
import com.link.base.base.common.model.InterObject;
import com.link.base.base.gateway.service.GatewayService;
import com.link.base.base.urlinfo.model.UrlInfo;
import com.link.base.base.user.model.User;
import com.link.base.cachedt.service.CacheDTService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.service.BasicServiceImpl;
import javax.annotation.Resource;

import com.link.core.basic.service.ServiceException;
import com.link.core.cllog.LCLogger;
import com.link.core.util.AppConstants;
import com.link.core.util.RedisUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>Title</p>
 * <p>Description</p>
 * <p>Company</p>
 *
 * @author yrf
 * @date 2016年8月4日  下午4:14:42
 */

@Service
public class AppDutyServiceImpl extends BasicServiceImpl<AppDuty> implements AppDutyService {
    /**
     * 职责URL的REDISKEY前缀
     */
    public static final String DUTY_URL_KEY_PEX = "DUTY_URL_" ;

    //APP职责更新时间对应的key
    public static final String LNK_DATA_UPD_APP_DUTY = "LNK_DATA_UPD_APP_DUTY";
    @Resource
    private AppDutyMapper appDutyMapper;

    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Resource
    private AppMenuUrlsService appMenuUrlsService;

    @Resource
    private GatewayService gatewayService;

    @Resource
    private CacheDTService cacheDTService;

    @Override
    public BasicMapper<AppDuty> getBasicMapper() throws Exception {
        if (appDutyMapper != null) {
            return appDutyMapper;
        }
        throw new ServiceException("PUBLIC-006");
    }

    @Override
    public List<User> queryDutyOfUserListPage(User record) throws Exception {
        return appDutyMapper.queryDutyOfUserListPage(record);
    }

    @Override
    public void addUserOfDutyInsert(User user) {
        checkAdminCorp(user, user.getDutyId());
        user.setAttr3(String.valueOf(keyGenerateDao.keyGenerate()));
        appDutyMapper.addUserOfDutyInsert(user);
    }

    @Override
    public void delUserOfDuty(InterObject record) throws Exception {
        appDutyMapper.delUserOfDuty(record);
    }

    @Override
    public List<UrlInfo> queryUnSelectUrlListPage(UrlInfo urlInfo) {
        if (StringUtils.isBlank(urlInfo.getAttr1())) {
            throw new ServiceException("DUTY-004");
        }
        return appDutyMapper.queryUnSelectUrlListPage(urlInfo);
    }

    @Override
    public List<User> queryUnSelectUserListPage(User user) {
        return appDutyMapper.queryUnSelectUserListPage(user);
    }

    /**
     * 某种情况下，000账套的登录人员会帮助其他公司账套创建职责的数据，所以
     * 如果当前账套为标准公司账套‘000’，则将职责的账套编号作为新建数据的账套编号
     *
     * @param record
     * @param DutyId
     */
    private void checkAdminCorp(BasicModel record, Long DutyId) {
        try {
//            if (StringUtils.equals(UserUtil.getUser().getCorpid(), AppConstants.ADMIN_CORPID)) {
            if (AppConstants.ADMIN_CORPID.equals(UserUtil.getUser().getCorpid())) {
                // 查询选中的职责信息
                AppDuty dutyParam = new AppDuty();
                dutyParam.setId(DutyId);
                AppDuty duty = queryById(dutyParam);
                record.setLoginCorpId(duty.getCorpid());
                record.setCorpid(duty.getCorpid());
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * 刷新用户所有职责权限
     *
     * @author 黄龙建
     * @date 2020年07月03日
     */
    public void refreshPermissions() throws Exception {
        try {
            AppDuty duty = new AppDuty();
            CoreUser user = UserUtil.getUser();
            duty.setLoginCorpId(user.getCorpid());
            duty.setPageFlag(false);
            duty.setCorpid(user.getLoginCorpId());
            List<AppDuty> dutyList = this.queryByExamplePage(duty);
            for (AppDuty dutyTmp : dutyList) {
                refreshPermByDutyId(dutyTmp);
            }
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * 刷新用户有一个职责的权限
     *
     * @author 黄龙建
     * @date 2020年07月03日
     */
    public void refreshPermByDutyId(AppDuty appDuty) throws Exception {
        LinkRedisClient jedis = null;
        try {
            Long id = appDuty.getId();
            if (id == null) {
                throw new Exception("职责id不能为空！");
            }
            jedis = RedisUtil.getJedis();

            //缓存数据缓存更新的时间
            cacheDTService.setCacheDataUpdateTime(LNK_DATA_UPD_APP_DUTY,jedis,null);

            //查询出当前职责信息。
            AppMenuUrls appMenuUrlsQuery = new AppMenuUrls();
            appMenuUrlsQuery.setDutyId(appDuty.getId());
            List<String> urlDutyUrlList = appMenuUrlsService.getUrlsByAppDuty(appMenuUrlsQuery);

            //获取得到相关的rediskey
            //为了统一，key都设置成大写的。
            String redisKey = DUTY_URL_KEY_PEX.concat("APP_").concat(String.valueOf(id)).toUpperCase();
            //先删除原有的
            jedis.del(redisKey);

            //把数据放入到一个数组中去。批量插入Redis中。
            String[] urlDutyUrlArray = new String[urlDutyUrlList.size()];
            urlDutyUrlList.toArray(urlDutyUrlArray);
            if (urlDutyUrlArray.length > 0) {
                jedis.lpush(redisKey, urlDutyUrlArray);
            }
            gatewayService.refreshAllCache("duty:".concat(redisKey));
        } finally {
            RedisUtil.returnResource(jedis);
        }
    }

    @Override
    public List<AppDuty> queryunSelectAppDutyOfUrlPage(AppDuty record) throws Exception {
        return appDutyMapper.queryunSelectAppDutyOfUrlPage(record);
    }
}
